package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.TradePaymentWindowBean;
import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;
import com.atguigu.utils.TimestampLtz3CompareUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @className: DwsTradePaymentSucWindow
 * @author: LinCong
 * @description:
 * @date: 2023/2/11 18:35
 * @version: 1.0
 */

//业务服务器（mysql）-> maxwell -> kafka(ods) -> flink(DwdTradeOrderPreProcess) -> kafka(dwd) ->
//flink(DwdTradeOrderDetail) -> kafka(dwd) -> flink(DwdTradePayDetailSuc) -> kafka(dwd)
//flink(DwsTradePaymentSucWindow) -> clickhouse
public class DwsTradePaymentSucWindow {
    public static void main(String[] args) throws Exception {
//        todo 1、获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);
        ////        1.1、开启checkpoint
//        env.enableCheckpointing(5 * 60000L, CheckpointingMode.EXACTLY_ONCE);
//        //设置checkpoint的超时时间,如果 Checkpoint在 10分钟内尚未完成说明该次Checkpoint失败,则丢弃。(默认10分钟)
//        env.getCheckpointConfig().setCheckpointTimeout(10 * 60000L);
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(120000L);
//        //固定延迟重启   （最多重启次数，每次重启的时间间隔）
//        env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 5000L));
////        1.2、设置状态后端
//        env.setStateBackend(new HashMapStateBackend());
//        System.setProperty("HADOOP_USER_NAME", "kevin");
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop3cluster/211126/ck");

//        todo 2、读取dwd层成功支付主题数据创建流
        String topic = "dwd_trade_pay_detail_suc";
        String groupId = "dws_trade_payment_suc_window";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId));

//        todo 3、将数据转化为json对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    System.out.println("JSONObject转换异常：" + value);
                }
            }
        });

//        todo 4、按照订单明细id分组
        KeyedStream<JSONObject, String> jsonObjKeyedByDetailIdDS = jsonObjDS.keyBy(json -> json.getString("order_detail_id"));

//        todo 5、使用状态编程保留最新的数据输出
        SingleOutputStreamOperator<JSONObject> filterDS = jsonObjKeyedByDetailIdDS.process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
            private ValueState<JSONObject> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                valueState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("value-state", JSONObject.class));
            }

            @Override
            public void processElement(JSONObject value, Context ctx, Collector<JSONObject> out) throws Exception {
                JSONObject state = valueState.value();
//                判断状态是否为null
                if (state == null) {
                    valueState.update(value);
                    ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000L);
                } else {
                    String stateRt = state.getString("row_op_ts");
                    String curRt = value.getString("row_op_ts");
//                    long divTs = microTs1 - microTs2;
//                    return divTs < 0 ? -1 : divTs == 0 ? 0 : 1;
                    int compare = TimestampLtz3CompareUtil.compare(stateRt, curRt);
//                    compare=1,即 divTs>0
                    if (compare != 1) {
//                        但定时器时间不更新
                        valueState.update(value);
                    }
                }
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<JSONObject> out) throws Exception {
//                super.onTimer(timestamp, ctx, out);
                JSONObject value = valueState.value();
                out.collect(value);

                valueState.clear();
            }
        });

//        todo 6、提取事件时间生成watermark
        SingleOutputStreamOperator<JSONObject> jsonObjWithWmDS = filterDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        String callbackTime = element.getString("callback_time");
                        return DateFormatUtil.toTs(callbackTime, true);
                    }
                }));

//        todo 7、按照user_id分组
        KeyedStream<JSONObject, String> keyedByUidDS = jsonObjWithWmDS.keyBy(json -> json.getString("user_id"));

//        todo 8、提取独立支付成功用户数和首次支付成功用户数
        SingleOutputStreamOperator<TradePaymentWindowBean> tradePaymentDS = keyedByUidDS.flatMap(new RichFlatMapFunction<JSONObject, TradePaymentWindowBean>() {
            private ValueState<String> lastDtState;
            private TradePaymentWindowBean tradePaymentWindowBean;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last-dt", String.class));
                tradePaymentWindowBean = new TradePaymentWindowBean();
            }

            @Override
            public void flatMap(JSONObject value, Collector<TradePaymentWindowBean> out) throws Exception {
                String lastDt = lastDtState.value();
                String curDt = value.getString("callback_time").split(" ")[0];
                // 支付成功独立用户数
                long paymentSucUniqueUserCount = 0l;
                // 支付成功新用户数
                long paymentSucNewUserCount = 0l;

                if (lastDt == null) {
                    paymentSucUniqueUserCount = 1l;
                    paymentSucNewUserCount = 1l;
                    lastDtState.update(curDt);
                } else if (!lastDt.equals(curDt)) {
                    paymentSucUniqueUserCount = 1l;
                    lastDtState.update(curDt);
                }

                if (paymentSucUniqueUserCount == 1l) {
                    tradePaymentWindowBean.setStt("");
                    tradePaymentWindowBean.setEdt("");
                    tradePaymentWindowBean.setPaymentSucUniqueUserCount(paymentSucUniqueUserCount);
                    tradePaymentWindowBean.setPaymentSucNewUserCount(paymentSucNewUserCount);
                    tradePaymentWindowBean.setTs(null);
                    out.collect(tradePaymentWindowBean);
                }
            }
        });

//        todo 9、开窗、聚合
        SingleOutputStreamOperator<TradePaymentWindowBean> resultDS = tradePaymentDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TradePaymentWindowBean>() {
                            @Override
                            public TradePaymentWindowBean reduce(TradePaymentWindowBean value1, TradePaymentWindowBean value2) throws Exception {
                                value1.setPaymentSucUniqueUserCount(value1.getPaymentSucUniqueUserCount() + value2.getPaymentSucUniqueUserCount());
                                value1.setPaymentSucNewUserCount(value1.getPaymentSucNewUserCount() + value2.getPaymentSucNewUserCount());
                                return value1;
                            }
                        },
                        new AllWindowFunction<TradePaymentWindowBean, TradePaymentWindowBean, TimeWindow>() {
                            @Override
                            public void apply(TimeWindow window, Iterable<TradePaymentWindowBean> values, Collector<TradePaymentWindowBean> out) throws Exception {
                                TradePaymentWindowBean next = values.iterator().next();

                                next.setTs(System.currentTimeMillis());
                                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                                out.collect(next);
                            }
                        });

//        todo 10、将数据写出到clickhouse
//        filterDS.print("filterDS>>>>>>");
        resultDS.print("resultDS>>>>>>");
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_trade_payment_suc_window values(?,?,?,?,?)"));

//        todo 11、启动任务
        env.execute("DwsTradePaymentSucWindow");
    }
}
